const { user_model } = require('../db/db')
const { code_status } = require('../utils/config.js')
module.exports = {
  /**
   * 检测用户是否登录
   * @param {*} req 
   * @param {*} res 
   * @param {*} done 
   * @returns 
   */
  verify: async function verify(req, res, done) {
    const jwt = this.jwt
    if (!req.raw.headers['authorization']) {
      res.send({
        statusCode: code_status.UN_AUTH,
        message: "",
        data: {}
      })
    }
    if (req.raw.headers['authorization'].indexOf('Bearer ') != -1) {

      jwt.verify(req.raw.headers['authorization'].slice(7), onVerify)
      async function onVerify(err, decoded) {
        console.log(decoded)
        if (err || !decoded._id) {
          return res.send({
            statusCode: code_status.UN_AUTH,
            message: "Token失效！",
            data: {}
          })
        }
        const user = await user_model.findById(decoded._id).exec();
        console.log(user)
        // const user = await db.collection('admin_users').findOne({ 'username': decoded.username })
        if (user === null) {
          console.log("?")
          res.send({
            statusCode: code_status.UN_AUTH,
            message: "用户无法找到，请重新登陆！",
            data: {}
          })
        }
      }
    } else {
      res.send({
        statusCode: code_status.UN_AUTH,
        message: "无Token！",
        data: {}
      })
    }

    //res.code(401).send({code:'401'})

  }
}